const axios = require("axios");
const { promisify } = require("util");
const sleep = promisify(setTimeout);
const fs = require("fs"); // 读写文件
const path = require("path"); // 定义文件路径
const xlsx = require("node-xlsx");
// 最大页数
const maxCount = 10;

const fetchData = async () => {
  // 是否还有下一页
  let hasNext = true;
  let activityIdList = [];
  let page = 1;
  const headers = {
    "User-Agent":
      "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
  };
  while (hasNext && (page <= maxCount)) {
    //爬取页面地址
    let pageUrl = `https://www.360pai.com/rest-web/open/activity/search?query=&perPage=20&page=${page}&partyCategoryId=&categoryId=2&subCategoryId=&busTypeName=&leaseAreaType=&assetLeaseType=&cityId=&townId=&provinceId=&areaId=&activityMode=&propertyNameId=&activityStatus=&orderBy=&beginPrice=&endPrice=`;
    const res = await axios(pageUrl, {
      headers,
    });
    const data = res.data || {};
    if (data) {
      console.log(`获取第${page}页 id 数据成功`);
    }
    let contentList = data.content.list || [];
    contentList.forEach((item) => {
      // 已经含有成交的状态标记，不需要下一页
      if (item.statusStr === "成交") {
        hasNext = false;
      } else if (item.statusStr === "即将开拍") {
        activityIdList.push([item.endAt, item.activityId]);
      }
    });
    page++;
    await sleep(1600);
  }
  return activityIdList;
};

const main = async () => {
  const activityIdList = await fetchData();
  const activityIdListUrl = activityIdList.map((item) => [
    item[0],
    `https://www.360pai.com/productDetail?id=${item[1]}`,
  ]);
  const data = [
    {
      name: "sheet1",
      data: [["截止时间", "链接"], ...activityIdListUrl],
    },
  ];
  const buffer = xlsx.build(data);
  // 写入文件
  fs.writeFile("详情链接-集合.xlsx", buffer, function (err) {
    if (err) {
      console.log("Write failed: " + err);
      return;
    }
    console.log("Write completed.");
  });
};

main();
